package com.zhiyun.hxzy.service;

import com.zhiyun.hxzy.dao.*;
import com.zhiyun.hxzy.domain.*;
import com.zhiyun.hxzy.domain.Dictionary;
import com.zhiyun.hxzy.util.Base64ToMultipartUtil;
import com.zhiyun.hxzy.util.UploadUtil;
import com.zhiyun.hxzy.domain.queryvo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.ArrayList;

@Service
@Transactional
public class HomeWorkService {
    @Autowired
    private HomeWorkDao homeWorkDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private DictionaryDao dictionaryDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private JdbcTemplate template;
    @Autowired
    private UploadUtil uploadUtil;
    @Autowired
    private HomeWorkInstructionDao homeWorkInstructionDao;


    public List<Homework> findbyTags(Long id) {
        List<Homework> byTags = homeWorkDao.findByTags(id);
        return byTags;
    }

    public List<Homework> findByStudentId(Long id) {
        List<Homework> byStudentId = homeWorkDao.findByStudentId(id);
        return byStudentId;
    }

    public Homework findById(Long homeworkId) {
        HomeWorkInstruction homeWorkInstruction = homeWorkInstructionDao.findByHomeworkId(homeworkId);
        Homework homework = homeWorkDao.findById(homeworkId).get();
        homework.setInstruction(homeWorkInstruction.getInstruction());
        return homework;
    }

    public Result uploadUimg(MultipartFile file) {
        String path = uploadUtil.upload(file);
        return new Result(path, true);
    }

    //老师点评作业
    public void commentHomework(Homework homework, Long teacherId) {
        Homework homework1 = findById(homework.getId());
        homework1.setScore(homework.getScore());
        homework1.setStar(homework.getStar());
        homework1.setTagEvaluate(homework.getTagEvaluate());
        homework1.setDescEvaluate(homework.getDescEvaluate());
        homework1.setTeacher(teacherDao.findById(teacherId).get());
        homework1.setCommentTime(new Date());
        int i = 0;
        if (homework1.getTeacher() != null) {
            homework1.setChecked(1);
        } else {
            homework1.setChecked(0);
        }
        homeWorkDao.save(homework1);
    }

    //（学生）查看学生待批改的作业
    public Page<Homework> findNotCommentHomeworkByStudent(int pageNum, int pageSize, Long studentId) {
        PageRequest pageRequest = PageRequest.of(pageNum,pageSize);
        Page<Homework> page = homeWorkDao.findByStudentId(studentId, 0, pageRequest);
        return page;
    }

    public List<Result> uploadImg(String[] urls) {
        List<Result> results = new ArrayList<>();
        if (urls != null) {
            if (urls[0].equals("data:image/jpeg;base64")) {
                urls[0] = null;
                urls[1] = ("data:image/jpeg;base64," + urls[1]);
                System.out.println(urls[1]);
            }
            for (String url : urls) {
                if (url != null && !url.contains("http")) {
                    MultipartFile multipartFile = Base64ToMultipartUtil.base64ToMultipart(url);
                    String path = uploadUtil.upload(multipartFile);
                    Result result = new Result(path, true);
                    results.add(result);
                }
            }
        }
        return results;
    }

    //（学生）学生修改待批改作业
    public void updateNotCommentHomeworkByStudent(Homework homework, Long[] studentId) {
        Homework homework1 = findById(homework.getId());
        homework1.setCoverImg(homework.getCoverImg());
        homework1.setTime(new Date());//修改作业提交时间
        homework1.setWorkName(homework.getWorkName());
        homework1.setInstruction(homework.getInstruction());
        homework1.setTags(homework.getTags());
        homework1.setContent(homework.getContent());
        homework1.setType(homework.getType());
        if (homework1.getType() == 1) {
            List<Student> students = new ArrayList<>();
            for (Long s : studentId) {
                students.add(studentDao.findById(s).get());
            }
            homework1.setStudents(students);
        }

        HomeWorkInstruction homeWorkInstruction = homeWorkInstructionDao.findByHomeworkId(homework.getId());
        homeWorkInstruction.setInstruction(homework.getInstruction());
        homeWorkInstructionDao.save(homeWorkInstruction);
        homeWorkDao.save(homework1);
    }

    //（学生）学生删除待批改作业
    public void delNotCommentHomeworkByStudent(Long homeworkId, Student student) {
        homeWorkDao.deleteByStudentIdAndHomeworkId(student.getId(), homeworkId);
        homeWorkDao.deleteById(homeworkId);
    }

    //（学生）查看学生已批改的作业
    public Page<Homework> findAlreadyCommentHomeworkByStudent(int pageNum, int pageSize, Long studentId) {
        PageRequest pageRequest = PageRequest.of(pageNum,pageSize);
        Page<Homework> page = homeWorkDao.findByStudentId(studentId, 1, pageRequest);
        return page;
    }

    //（老师）查看老师待批改的作业
    public Page<Homework> findNotCommentHomeworkByTeacher(int pageNum, int pageSize, Long teacherId,Long classId) {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        Page<Homework> page = null;
        System.out.println(classId);
        if (classId != null && classId != -1){
           page = homeWorkDao.findHomeworkByTeacherIdAndClassId(classId, 0, pageRequest);
        }else {
            page = homeWorkDao.findHomeworkByTeacherId(teacherId,0,pageRequest);
        }
        return page;
    }
    //（老师）查看老师已批改的作业
    public Page<Homework> findAlreadyCommentHomeworkByTeacher(int pageNum, int pageSize, Long teacherId) {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        Page<Homework> page = homeWorkDao.findHomeworkByTeacherId(teacherId,1,pageRequest);
        return page;
    }

    //查寻所有作业
    public List<Homework> findAll() {
        return homeWorkDao.findAll();
    }


    //查询所有标签
    public List<Dictionary> findByType() {
        return dictionaryDao.findByType("标签");
    }

    //查询所有内容
    public List<Dictionary> findByContent() {
        return dictionaryDao.findByType("内容");
    }

    //查询所有类型
    public List<Dictionary> findByForm() {
        return dictionaryDao.findByType("类型");
    }

    //查询所有评价标签
    public List<Dictionary> findByAssess() {
        return dictionaryDao.findByType("评价标签");
    }

    //模糊查询作品
    public List<Homework> findByWorkName(String workName) {
        List<Homework> all = null;
        if (!workName.equals("")) {
            all = homeWorkDao.findAllByWorkName(workName);
        }
        return all;
    }

    //查询所有作业
    public Page<Homework> findAllHomeWork(Long xueXiao,Long banji, Long xuesheng, String startTime, String endTime, String paixu,String keywords,Integer pageSize, Integer pageNum, List<String> biaoqianList, List<String> neirongList, List<String> leixingList) {
        String str = "select * from hx_homework where checked = 1 ";
        if (biaoqianList != null && biaoqianList.size() != 0) {
            String biaoqianStr = " and tags in(";
            for (String biaoqian : biaoqianList) {
                biaoqianStr += ("'" + biaoqian + "',");
            }
            biaoqianStr = biaoqianStr.substring(0, biaoqianStr.length() - 1);
            biaoqianStr += ") ";
            str += biaoqianStr;
        }
        if (neirongList != null && neirongList.size() != 0) {
            String neirongStr = " and content in(";
            for (String neirong : neirongList) {
                neirongStr += ("'" + neirong + "',");
            }
            neirongStr = neirongStr.substring(0, neirongStr.length() - 1);
            neirongStr += ") ";
            str += neirongStr;
        }
        if (leixingList != null && leixingList.size() != 0) {
            String leixingStr = " and type in(";
            for (String leixing : leixingList) {
                if ("个人作业".equals(leixing)) {
                    leixingStr += ("0,");
                }
                if ("小组作业".equals(leixing)) {
                    leixingStr += ("1,");
                }
            }
            leixingStr = leixingStr.substring(0, leixingStr.length() - 1);
            leixingStr += ") ";
            str += leixingStr;
        }
        if(keywords != null){
            str += " and workName like '%"+keywords+"%' ";
        }
        if (banji != null) {
            str += " and id IN (SELECT hid FROM hx_student_homework WHERE sid IN (SELECT id FROM hx_student WHERE classid = " + banji + "))";
        }
        if (xuesheng != null) {
            str += " and id IN (SELECT hid FROM hx_student_homework WHERE sid = " + xuesheng + ")";
        }
        if (startTime != null) {
            str += " and time >= '"+startTime+"'";
        }
        if (endTime != null) {
            str += " and time <= '"+endTime+"'";
        }
        if (xueXiao != null){
            str += " and id in (SELECT hid FROM hx_student_homework where sid in (SELECT id FROM hx_student WHERE classid in (select id from hx_classes where schoolId = "+xueXiao+")))";
        }
        str += " order by time desc ";
        String strCount = str.replace("*","count(id)");
        int startIndex = (pageNum-1)*pageSize;
        str += " limit "+startIndex+","+pageSize;
        List<Homework> homeworks = template.query(str, new BeanPropertyRowMapper<>(Homework.class));
        Integer count = template.queryForObject(strCount, Integer.class);
        // 每个Homework查询学生信息
        for(Homework homework:homeworks){
            List<Student> students = studentDao.findByHid(homework.getId());
            homework.setStudents(students);
        }
        Pageable pageable = PageRequest.of(pageNum-1, pageSize);
        Page<Homework> page = new PageImpl<>(homeworks,pageable,count);
        return page;
    }

    //查询所有作业
    public Page<Homework> findAll(int pageNum, int pageSize,Long sid) {
        if (pageNum < 0) {
            pageNum = 0;
        }

        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        if (sid == null){
            return homeWorkDao.findAll(pageRequest);
        }
        Page<Homework> all = homeWorkDao.findByStudentId(sid,pageRequest);
        return all;
    }

    public void delHomeWork1(Long[] id) {
        for (Long i : id) {
            homeWorkDao.deleteHomeWorkStudent(i);
        }
    }
    public void del(Long[] id) {
        for (Long i : id) {
            homeWorkDao.deleteById(i);
        }
    }

    //根据老师id，查询未批改的作业
    public Homework findByTeacherIdAndChecked(Long teacherId){
//        List<Homework> homeworkList = homeWorkDao.findByTeacherIdAndChecked(teacherId, 0);
//        if (homeworkList.size()==0){
//            return null;
//        }else {
//            return homeworkList.get(0);
//        }
        List<Homework> f = homeWorkDao.f(teacherId, 0);
        if (f.size()==0){
            return null;
        }else {
            return f.get(0);
        }

    }
}
